using System;
using System.Collections.Generic;
using Mall.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Mall.Api.ParamModel;
using Newtonsoft.Json;
using Mall.Api.Repository;
using Mall.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Mall.Api.Filters;
using Microsoft.AspNetCore.Authentication;

namespace Mall.Api.Controllers
{
    /// <summary>
    /// 修改个人信息
    /// </summary>


    [Authorize]

    [ApiController]
    [Route("amend")]
    public class PersonalInformationController : ControllerBase
    {

        private IRepository<Users> _users;
        private IRepository<Supplier> _supplier;
        private readonly IConfiguration _configuration;
        private IRepository<GoodsReceivingInformation> _goodsReceivingInformation;

        public PersonalInformationController(IConfiguration configuration, IRepository<Supplier> supplier, IRepository<Users> users, IRepository<GoodsReceivingInformation> goodsReceivingInformation)
        {


            _users = users;
            _supplier = supplier;
            _configuration = configuration;
            _goodsReceivingInformation = goodsReceivingInformation;
        }

        /// <summary>
        /// 获取登入用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public dynamic Get()
        {

            var claims = base.HttpContext.AuthenticateAsync().Result
           .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;

            // var users = _users.GetById(int.Parse(userid));
            // var userAddress = from users in _users.Table
            //                   join address in _goodsReceivingInformation.Table on users.Id equals address.UsersId
            //                   where users.IsActived == true
            //                   select new
            //                   {
            //                       Nickname = users.Nickname,
            //                       Username = users.Username,
            //                       Password = users.Password,
            //                       Banlance = users.Balance,
            //                       Txcolor = users.Txcolor,
            //                       Bgcolor = users.Bgcolor,
            //                     Consignee=address.Consignee,
            //                     CPhone =address.CPhone,
                                
            //                     ShippingAddress=address.ShippingAddress

            //                   };
            var users = _users.Table.Where(u =>u.Id==int.Parse(userid)).FirstOrDefault();

            var addressList = _goodsReceivingInformation.Table.Where(a =>a.UsersId==int.Parse(userid)).FirstOrDefault();


            if (users == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = new{
                        users,
                        addressList
                    },
                    Msg = "获取用户信息成功"
                });

        }



        // /// <summary>
        // /// 获取用户收货地址信息
        // /// </summary>
        // /// <returns></returns>
        // [HttpGet("address/{id}")]
        // public dynamic GetAddress()
        // {

        //     var claims = base.HttpContext.AuthenticateAsync().Result
        //    .Principal.Claims.FirstOrDefault().Subject.Claims;


        //     var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;


        //     var b = _goodsReceivingInformation.Table.Single(b => b.UsersId == int.Parse(userid)).Id;
        //     var address = _goodsReceivingInformation.GetById(b);

        //     if (address == null)
        //     {
        //         return new
        //         {
        //             Code = 1004,
        //             Data = "",
        //             Msg = "指定用户收货地址不存在！"
        //         };

        //     }
        //     return new
        //     {
        //         Code = 200,
        //         Data = address,
        //         Msg = "获取用户地址成功^_^"
        //     };

        // }







        /// <summary>
        /// 修改我的昵称
        /// </summary>
        /// <returns></returns>
        [HttpPut("amendnickname")]
        public dynamic Put(NewNickname model)
        {

            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var users = _users.GetById(int.Parse(userid));
            if (users != null)
            {

                users.Nickname = model.Nickname;
                users.UpdatedTime = DateTime.Now;
                _users.Update(users);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = users,
                    Msg = string.Format("你修改或的用户的id为：{0}，已经修改成功，请注意查收", userid)
                });
            }
            else
            {

                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }



        }






        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPut("amendpassword")]
        public dynamic PutPassword(NewAmendPassword model)
        {

            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var users = _users.GetById(int.Parse(userid));
            if (users != null)
            {
                if (model.NewPassword == model.ConfirmPassword && model.Password == users.Password)
                {

                    users.Password = model.NewPassword;
                    users.UpdatedTime = DateTime.Now;
                    _users.Update(users);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = users,
                        Msg = string.Format("你修改的用户的id为：{0}，已经修改成功，请注意查收", userid)
                    });


                }
                else
                {
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = "",
                        Msg = string.Format("旧密码不正确或两次输入的密码不一致！")
                    });

                }


            }
            else
            {

                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }



        }







        /// <summary>
        /// 修改地址
        /// </summary>
        /// <returns></returns>
        [HttpPut("amendaddress")]
        public dynamic PutAddress(NewAmendShippingAddress model)
        {

            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var a = _goodsReceivingInformation.Table.Single(a => a.UsersId == int.Parse(userid)).Id;
            var goods = _goodsReceivingInformation.GetById(a);
            if (goods != null)
            {

                goods.ShippingAddress = model.ShippingAddress;
                goods.UpdatedTime = DateTime.Now;
                _goodsReceivingInformation.Update(goods);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = goods,
                    Msg = string.Format("你修改或的用户的id为：{0}，已经修改成功，请注意查收", userid)
                });
            }
            else
            {

                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的用户不存在，请确认后重试"
                });
            }



        }






        /// <summary>
        /// 添加收货地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>

        [HttpPost]
        public string Post(NewAddAddress model)
        {
            var claims = base.HttpContext.AuthenticateAsync().Result
            .Principal.Claims.FirstOrDefault().Subject.Claims;


            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var usersId = userid;
            var consignee = model.Consignee.Trim();
            var cPhone = model.CPhone.Trim();
            var shippingAddress = model.ShippingAddress.Trim();


            if (string.IsNullOrEmpty(shippingAddress))
            {
                var tmp = new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "地址不能为空，请确认后重试"
                };
                return JsonHelper.Serialize(tmp);
            }


            var address = new GoodsReceivingInformation
            {
                Users = _users.Table.Single(u => u.Id == int.Parse(usersId)),
                Consignee = consignee,
                CPhone = cPhone,
                ShippingAddress = shippingAddress

            };

            _goodsReceivingInformation.Insert(address);


            var res = new
            {
                Code = 200,
                Data = new
                {
                    Address = address

                },
                Msg = "添加地址成功"
            };
            return JsonHelper.Serialize(res);
        }







    }

}